package com.room.search.web.rest;

import com.room.search.domain.RoomSearchCommunity;
import com.room.search.repository.RoomSearchCommunityRepository;
import com.room.search.web.rest.errors.BadRequestAlertException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.ResponseUtil;

/**
 * REST controller for managing {@link RoomSearchCommunity}.
 */
@RestController
@RequestMapping("/api")
@Transactional
public class RoomCommunitySearchResource {

    private final Logger log = LoggerFactory.getLogger(RoomCommunitySearchResource.class);

    private static final String ENTITY_NAME = "roomCommunitySearch";

    @Value("${jhipster.clientApp.name}")
    private String applicationName;

    private final RoomSearchCommunityRepository roomSearchCommunityRepository;

    public RoomCommunitySearchResource(RoomSearchCommunityRepository roomSearchCommunityRepository) {
        this.roomSearchCommunityRepository = roomSearchCommunityRepository;
    }

    /**
     * {@code POST  /room-community-searches} : Create a new roomCommunitySearch.
     *
     * @param roomSearchCommunity the roomCommunitySearch to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new roomCommunitySearch, or with status {@code 400 (Bad Request)} if the roomCommunitySearch has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("/room-community-searches")
    public ResponseEntity<RoomSearchCommunity> createRoomCommunitySearch(@RequestBody RoomSearchCommunity roomSearchCommunity)
        throws URISyntaxException {
        log.debug("REST request to save RoomCommunitySearch : {}", roomSearchCommunity);
        if (roomSearchCommunity.getId() != null) {
            throw new BadRequestAlertException("A new roomCommunitySearch cannot already have an ID", ENTITY_NAME, "idexists");
        }
        RoomSearchCommunity result = roomSearchCommunityRepository.save(roomSearchCommunity);
        return ResponseEntity
            .created(new URI("/api/room-community-searches/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * {@code PUT  /room-community-searches/:id} : Updates an existing roomCommunitySearch.
     *
     * @param id the id of the roomCommunitySearch to save.
     * @param roomSearchCommunity the roomCommunitySearch to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated roomCommunitySearch,
     * or with status {@code 400 (Bad Request)} if the roomCommunitySearch is not valid,
     * or with status {@code 500 (Internal Server Error)} if the roomCommunitySearch couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/room-community-searches/{id}")
    public ResponseEntity<RoomSearchCommunity> updateRoomCommunitySearch(
        @PathVariable(value = "id", required = false) final Long id,
        @RequestBody RoomSearchCommunity roomSearchCommunity
    ) throws URISyntaxException {
        log.debug("REST request to update RoomCommunitySearch : {}, {}", id, roomSearchCommunity);
        if (roomSearchCommunity.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, roomSearchCommunity.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!roomSearchCommunityRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        RoomSearchCommunity result = roomSearchCommunityRepository.save(roomSearchCommunity);
        return ResponseEntity
            .ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, roomSearchCommunity.getId().toString()))
            .body(result);
    }

    /**
     * {@code PATCH  /room-community-searches/:id} : Partial updates given fields of an existing roomCommunitySearch, field will ignore if it is null
     *
     * @param id the id of the roomCommunitySearch to save.
     * @param roomSearchCommunity the roomCommunitySearch to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated roomCommunitySearch,
     * or with status {@code 400 (Bad Request)} if the roomCommunitySearch is not valid,
     * or with status {@code 404 (Not Found)} if the roomCommunitySearch is not found,
     * or with status {@code 500 (Internal Server Error)} if the roomCommunitySearch couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PatchMapping(value = "/room-community-searches/{id}", consumes = { "application/json", "application/merge-patch+json" })
    public ResponseEntity<RoomSearchCommunity> partialUpdateRoomCommunitySearch(
        @PathVariable(value = "id", required = false) final Long id,
        @RequestBody RoomSearchCommunity roomSearchCommunity
    ) throws URISyntaxException {
        log.debug("REST request to partial update RoomCommunitySearch partially : {}, {}", id, roomSearchCommunity);
        if (roomSearchCommunity.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, roomSearchCommunity.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!roomSearchCommunityRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        Optional<RoomSearchCommunity> result = roomSearchCommunityRepository
            .findById(roomSearchCommunity.getId())
            .map(existingRoomCommunitySearch -> {
                if (roomSearchCommunity.getCommunityId() != null) {
                    existingRoomCommunitySearch.setCommunityId(roomSearchCommunity.getCommunityId());
                }
                if (roomSearchCommunity.getAverage() != null) {
                    existingRoomCommunitySearch.setAverage(roomSearchCommunity.getAverage());
                }

                return existingRoomCommunitySearch;
            })
            .map(roomSearchCommunityRepository::save);

        return ResponseUtil.wrapOrNotFound(
            result,
            HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, roomSearchCommunity.getId().toString())
        );
    }

    /**
     * {@code GET  /room-community-searches} : get all the roomCommunitySearches.
     *
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of roomCommunitySearches in body.
     */
    @GetMapping("/room-community-searches")
    public List<RoomSearchCommunity> getAllRoomCommunitySearches() {
        log.debug("REST request to get all RoomCommunitySearches");
        return roomSearchCommunityRepository.findAll();
    }

    /**
     * {@code GET  /room-community-searches/:id} : get the "id" roomCommunitySearch.
     *
     * @param id the id of the roomCommunitySearch to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the roomCommunitySearch, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/room-community-searches/{id}")
    public ResponseEntity<RoomSearchCommunity> getRoomCommunitySearch(@PathVariable Long id) {
        log.debug("REST request to get RoomCommunitySearch : {}", id);
        Optional<RoomSearchCommunity> roomCommunitySearch = roomSearchCommunityRepository.findById(id);
        return ResponseUtil.wrapOrNotFound(roomCommunitySearch);
    }

    /**
     * {@code DELETE  /room-community-searches/:id} : delete the "id" roomCommunitySearch.
     *
     * @param id the id of the roomCommunitySearch to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/room-community-searches/{id}")
    public ResponseEntity<Void> deleteRoomCommunitySearch(@PathVariable Long id) {
        log.debug("REST request to delete RoomCommunitySearch : {}", id);
        roomSearchCommunityRepository.deleteById(id);
        return ResponseEntity
            .noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString()))
            .build();
    }
}
